<template>
  <div class="orders">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <h2>订单管理</h2>
      <el-button type="primary" @click="handleExport" icon="Download">
        导出订单
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单号"
            clearable
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card>
      <el-table
        :data="filteredOrders"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120" />
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleView(scope.row)"
              icon="View"
            >
              查看
            </el-button>
            <el-button
              v-if="scope.row.status === 'paid'"
              size="small"
              type="success"
              @click="handleShip(scope.row)"
              icon="Truck"
            >
              发货
            </el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              size="small"
              type="danger"
              @click="handleCancel(scope.row)"
              icon="Close"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
    >
      <div v-if="selectedOrder" class="order-detail">
        <!-- 订单基本信息 -->
        <el-descriptions title="订单信息" :column="2" border>
          <el-descriptions-item label="订单号">
            {{ selectedOrder.orderNo }}
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">
            {{ selectedOrder.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="客户姓名">
            {{ selectedOrder.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ selectedOrder.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(selectedOrder.status)">
              {{ getStatusLabel(selectedOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            {{ selectedOrder.paymentMethod }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 收货地址 -->
        <el-descriptions title="收货地址" :column="1" border style="margin-top: 20px">
          <el-descriptions-item label="详细地址">
            {{ selectedOrder.address }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 商品列表 -->
        <div style="margin-top: 20px">
          <h4>商品列表</h4>
          <el-table :data="selectedOrder.items" style="width: 100%">
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="price" label="单价" width="120">
              <template #default="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column label="小计" width="120">
              <template #default="scope">
                ¥{{ scope.row.price * scope.row.quantity }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 订单金额 -->
        <div style="margin-top: 20px; text-align: right">
          <h3>订单总额: ¥{{ selectedOrder.totalAmount }}</h3>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

/**
 * Vue子应用订单管理页面
 * @description 提供订单的查看、处理和管理功能
 */
export default {
  name: 'Orders',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const detailDialogVisible = ref(false)
    const selectedOrder = ref(null)
    const selectedRows = ref([])

    // 搜索表单
    const searchForm = reactive({
      orderNo: '',
      status: '',
      dateRange: []
    })

    // 模拟订单数据
    const orders = ref([
      {
        id: 1,
        orderNo: 'ORD20231201001',
        customerName: '张三',
        phone: '13800138000',
        totalAmount: 8999,
        status: 'paid',
        paymentMethod: '支付宝',
        createTime: '2023-12-01 14:30:00',
        address: '北京市朝阳区某某街道123号',
        items: [
          { name: 'iPhone 15 Pro', price: 8999, quantity: 1 }
        ]
      },
      {
        id: 2,
        orderNo: 'ORD20231201002',
        customerName: '李四',
        phone: '13900139000',
        totalAmount: 1598,
        status: 'pending',
        paymentMethod: '微信支付',
        createTime: '2023-12-01 15:20:00',
        address: '上海市浦东新区某某路456号',
        items: [
          { name: 'AirPods Pro', price: 1999, quantity: 1 },
          { name: 'Nike运动鞋', price: 599, quantity: 1 }
        ]
      },
      {
        id: 3,
        orderNo: 'ORD20231201003',
        customerName: '王五',
        phone: '13700137000',
        totalAmount: 7999,
        status: 'shipped',
        paymentMethod: '银行卡',
        createTime: '2023-12-01 16:10:00',
        address: '广州市天河区某某大道789号',
        items: [
          { name: 'MacBook Air', price: 7999, quantity: 1 }
        ]
      }
    ])

    // 计算属性：过滤后的订单列表
    const filteredOrders = computed(() => {
      let result = orders.value

      if (searchForm.orderNo) {
        result = result.filter(item => 
          item.orderNo.toLowerCase().includes(searchForm.orderNo.toLowerCase())
        )
      }

      if (searchForm.status) {
        result = result.filter(item => item.status === searchForm.status)
      }

      if (searchForm.dateRange && searchForm.dateRange.length === 2) {
        const [startDate, endDate] = searchForm.dateRange
        result = result.filter(item => {
          const orderDate = item.createTime.split(' ')[0]
          return orderDate >= startDate && orderDate <= endDate
        })
      }

      total.value = result.length
      return result
    })

    // 获取状态标签类型
    const getStatusType = (status) => {
      const types = {
        pending: 'warning',
        paid: 'primary',
        shipped: 'success',
        completed: 'success',
        cancelled: 'danger'
      }
      return types[status] || 'default'
    }

    // 获取状态标签文本
    const getStatusLabel = (status) => {
      const labels = {
        pending: '待付款',
        paid: '已付款',
        shipped: '已发货',
        completed: '已完成',
        cancelled: '已取消'
      }
      return labels[status] || status
    }

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      ElMessage.success('搜索完成')
    }

    // 处理重置
    const handleReset = () => {
      Object.assign(searchForm, {
        orderNo: '',
        status: '',
        dateRange: []
      })
      currentPage.value = 1
    }

    // 处理导出
    const handleExport = () => {
      ElMessage.success('订单导出功能开发中...')
    }

    // 处理查看订单详情
    const handleView = (row) => {
      selectedOrder.value = row
      detailDialogVisible.value = true
    }

    // 处理发货
    const handleShip = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要发货订单 "${row.orderNo}" 吗？`,
          '确认发货',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        row.status = 'shipped'
        ElMessage.success('发货成功')
      } catch {
        // 用户取消操作
      }
    }

    // 处理取消订单
    const handleCancel = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要取消订单 "${row.orderNo}" 吗？`,
          '确认取消',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        row.status = 'cancelled'
        ElMessage.success('订单已取消')
      } catch {
        // 用户取消操作
      }
    }

    // 处理表格选择
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }

    // 处理分页
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    // 组件挂载时初始化数据
    onMounted(() => {
      total.value = orders.value.length
    })

    return {
      loading,
      currentPage,
      pageSize,
      total,
      detailDialogVisible,
      selectedOrder,
      selectedRows,
      searchForm,
      filteredOrders,
      getStatusType,
      getStatusLabel,
      handleSearch,
      handleReset,
      handleExport,
      handleView,
      handleShip,
      handleCancel,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
/* 订单管理页面样式 */
.orders {
  max-width: 1200px;
  margin: 0 auto;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 订单详情样式 */
.order-detail h4 {
  margin: 0 0 16px 0;
  color: #303133;
}

.order-detail h3 {
  margin: 0;
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-bottom: 16px;
  }
}
</style> 